package com.hugeyurt.service.impl;

import java.lang.reflect.Field;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;

import com.hugeyurt.po.WeiXinMsg;
import com.hugeyurt.service.WeiXinService;

@Service
public class WeiXinServiceImpl  implements WeiXinService
{

	@Override
	public WeiXinMsg getMsg(String xml)
	{
		WeiXinMsg msgPo=null;
		try{
		  if(xml==null||xml.length()<=0) return null;
	       Document document = DocumentHelper.parseText(xml);  
           Element root = document.getRootElement();  
           Iterator<?> iter = root.elementIterator();
            msgPo=new WeiXinMsg();
            Class c=msgPo.getClass();
            
            while(iter.hasNext()){  
              Element ele = (Element)iter.next();  
           
               Field field =null;
                try {
                	field=c.getDeclaredField(ele.getName()); 
                }catch(Exception e)
                {
                	//e.printStackTrace();
                }
                if(field==null) continue;
                field.setAccessible(true);
                field.set(msgPo, ele.getText());
            }  
		}catch (Exception ex){
			ex.printStackTrace();
		}
		return msgPo;
		
	}

	@Override
	public String Text2Xml(WeiXinMsg msg) {
		// TODO Auto-generated method stub
		StringBuffer stf=new StringBuffer(2000);
		stf.append("<xml><ToUserName>");
		stf.append("<![CDATA["+msg.getFromUserName()+"]]></ToUserName>");
		stf.append("<FromUserName><![CDATA["+msg.getToUserName()+"]]></FromUserName>");
		stf.append("<CreateTime>"+msg.getCreateTime()+"</CreateTime>");
		stf.append("<MsgType><![CDATA[text]]></MsgType>");
		stf.append("<Content><![CDATA["+msg.getContent()+"]]></Content>");
		stf.append("<MsgId>"+msg.getMsgId()+"</MsgId></xml>"); 
		//System.out.println(stf.toString());
		return stf.toString();
	}

}
